import logging

import yaml
import os

from util.log_util import get_the_logger
logger = get_the_logger(__name__)


# keep int string like string type
class SafeStringLoader(yaml.SafeLoader):
    def construct_yaml_int(self, node):
        return str(self.construct_scalar(node))


SafeStringLoader.add_constructor(
    'tag:yaml.org,2002:int',
    SafeStringLoader.construct_yaml_int
)


def read_fund_yml(f):
    """读取基金配置文件"""
    try:
        with open(f, 'r', encoding='utf-8') as f:
            return yaml.load(f, Loader=SafeStringLoader) or {}
    except Exception as e:
        logger.error(f"读取 YAML 文件失败: {e}")
        return {}


def write_fund_yml(data, f):
    """写入基金配置文件"""
    try:
        with open(f, 'w', encoding='utf-8') as f:
            yaml.safe_dump(data, f, allow_unicode=True, default_flow_style=False)
        return True
    except Exception as e:
        logger.info(f"写入 YAML 文件失败: {e}")
        return False


def yml_to_csv_path(yaml_file_list):
    from fund.get_history_data import read_funds_from_yml_list
    period = 'daily'
    csv_output_path_list = []
    fund_code_list, m = read_funds_from_yml_list(yaml_file_list)
    for fund_code in fund_code_list:
        csv_output_path = f'fund/history_data/{fund_code}-{period}.csv'
        csv_output_path_list.append(csv_output_path)
    return csv_output_path_list


def fund_code_to_csv_path(fund_code_list):
    period = 'daily'
    csv_output_path_list = []
    for fund_code in fund_code_list:
        csv_output_path = f'fund/history_data/{fund_code}-{period}.csv'
        csv_output_path_list.append(csv_output_path)
    return csv_output_path_list